package com.hy.mydesktop.client.example;   
  
import java.util.ArrayList;   
import java.util.List;   
import java.util.Map;   
 
import com.extjs.gxt.samples.resources.client.Resources;   
import com.extjs.gxt.ui.client.Registry;   
import com.extjs.gxt.ui.client.Style.SortDir;   
import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.data.BasePagingLoadConfig;   
import com.extjs.gxt.ui.client.data.BasePagingLoader;   
import com.extjs.gxt.ui.client.data.DataReader;
import com.extjs.gxt.ui.client.data.ModelData;   
import com.extjs.gxt.ui.client.data.PagingLoadConfig;   
import com.extjs.gxt.ui.client.data.PagingLoadResult;   
import com.extjs.gxt.ui.client.data.PagingLoader;   
import com.extjs.gxt.ui.client.data.RpcProxy;   
import com.extjs.gxt.ui.client.event.Events;   
import com.extjs.gxt.ui.client.event.GridEvent;   
import com.extjs.gxt.ui.client.event.Listener;   
import com.extjs.gxt.ui.client.store.ListStore;   
import com.extjs.gxt.ui.client.widget.ContentPanel;   
import com.extjs.gxt.ui.client.widget.LayoutContainer;   
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;   
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;   
import com.extjs.gxt.ui.client.widget.grid.Grid;   
import com.extjs.gxt.ui.client.widget.layout.FitLayout;   
import com.extjs.gxt.ui.client.widget.layout.FlowLayout;   
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;   
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;   
import com.google.gwt.user.client.Element;   
import com.google.gwt.user.client.rpc.AsyncCallback;   
import com.hy.mydesktop.client.component.meta.GridPagingLoadConfigModel;
import com.hy.mydesktop.client.rpc.ServiceInvoker;
import com.hy.mydesktop.client.rpc.ServiceInvokerAsync;
import com.hy.mydesktop.client.rpc.reader.GxtToSeamServiceResultPagingReader;
import com.hy.mydesktop.shared.persistence.domain.gxt.constant.MetaDataConstants;
import com.hy.mydesktop.shared.rpc.meta.GxtToSeamServiceParameter;
import com.hy.mydesktop.shared.rpc.meta.GxtToSeamServiceResult;
  
public class PagingGridExample2012_2_22 extends LayoutContainer {   
  
  @Override  
  protected void onRender(Element parent, int index) {   
    super.onRender(parent, index);   
    final ServiceInvokerAsync service = GWT.create(ServiceInvoker.class);

    //final ExampleServiceAsync service = (ExampleServiceAsync) Registry.get(Examples.SERVICE);   
  
    FlowLayout layout = new FlowLayout(10);   
    setLayout(layout);   
  
    /*RpcProxy<PagingLoadResult<Post>> proxy = new RpcProxy<PagingLoadResult<Post>>() {   
      @Override  
      public void load(Object loadConfig, AsyncCallback<PagingLoadResult<Post>> callback) {   
        service.getPosts((PagingLoadConfig) loadConfig, callback);   
      }   
    };   
  
    // loader   
    final PagingLoader<PagingLoadResult<ModelData>> loader = new BasePagingLoader<PagingLoadResult<ModelData>>(   
        proxy);   
    loader.setRemoteSort(true);   
  
    ListStore<ModelData> store = new ListStore<ModelData>(loader); */  
  
    RpcProxy<GxtToSeamServiceResult> proxy = new RpcProxy<GxtToSeamServiceResult>(){
    	@Override
    	public void load(final DataReader<GxtToSeamServiceResult> reader, final Object loadConfig,
    		      final AsyncCallback<GxtToSeamServiceResult> callback) {
    		    load(loadConfig, new AsyncCallback<GxtToSeamServiceResult>() {

    		    	@Override
    		      public void onFailure(Throwable caught) {
    		        callback.onFailure(caught);
    		      }

    		     /* @SuppressWarnings("unchecked")
    		      public void onSuccess(Object result) {
    		        try {
    		        	GxtToSeamServiceResult data = null;
    		          if (reader != null) {
    		            data = reader.read(loadConfig, result);
    		          } else {
    		            data = (GxtToSeamServiceResult) result;
    		          }
    		          callback.onSuccess(data);
    		        } catch (Exception e) {
    		          callback.onFailure(e);
    		        }
    		      }*/

				@Override
				public void onSuccess(GxtToSeamServiceResult result) {
					 try {
	    		        	GxtToSeamServiceResult data = null;
	    		          if (reader != null) {
	    		            data = reader.read(loadConfig, result);
	    		          } else {
	    		            data = (GxtToSeamServiceResult) result;
	    		          }
	    		          callback.onSuccess(data);
	    		        } catch (Exception e) {
	    		          callback.onFailure(e);
	    		          e.printStackTrace();
	    		        }
					
				}

    		    });
    		  }

		@Override
		protected void load(Object loadConfig,
				AsyncCallback<GxtToSeamServiceResult> callback) {
			//TODO 需要进行结构转换
			BaseModel[] methodArguments = new BaseModel[1];
			methodArguments[0] = new GridPagingLoadConfigModel();
			if (loadConfig instanceof PagingLoadConfig) {
				methodArguments[0] = new GridPagingLoadConfigModel(
						((PagingLoadConfig)loadConfig).getOffset(),	
						((PagingLoadConfig)loadConfig).getLimit()
					);
			}
			System.err.println("####GridDataLoadView####((PagingLoadConfig)loadConfig).getLimit()"+((PagingLoadConfig)loadConfig).getLimit());						
			/*gxtToSeamServiceParameter.setServiceComponentName("com.hy.mydesktop.server.business.PersonService");22
			gxtToSeamServiceParameter.setServiceMethodName("listPage");*/
			final GxtToSeamServiceParameter gxtToSeamServiceParameter = new GxtToSeamServiceParameter();

			//PresenterHandleUtil.printPresenterInfoForEventHandle(this,event);
			gxtToSeamServiceParameter.setMethodArgumentsType(MetaDataConstants.MODELDATA_ARRAY);
			gxtToSeamServiceParameter.setServiceComponentName("positionTypeService");
			gxtToSeamServiceParameter.setServiceMethodName("getPageOfPersistentEntities");
			gxtToSeamServiceParameter.setMethodArguments(methodArguments );	

			service.callService(gxtToSeamServiceParameter, callback);
			AsyncCallback asyncCallback =callback;
			//asyncCallback.onFailure(caught)
			//PagingLoadResult pagingLoadResult = new PagingLoadResult<Data>() {
			//};
			
		}};
		 GxtToSeamServiceResultPagingReader<ModelData> pagingReader =  new GxtToSeamServiceResultPagingReader<ModelData>();;

		final BasePagingLoader<PagingLoadResult<ModelData>> pageLoader =  new  BasePagingLoader<PagingLoadResult<ModelData>>(proxy,pagingReader);
	
	final  ListStore<ModelData> listStore = new ListStore<ModelData>(pageLoader);
	
    final PagingToolBar toolBar = new PagingToolBar(5);   
    toolBar.bind(pageLoader);   
  
    List<ColumnConfig> columns = new ArrayList<ColumnConfig>();   
    columns.add(new ColumnConfig("forum", "Forum", 150));   
    columns.add(new ColumnConfig("username", "Username", 100));   
    columns.add(new ColumnConfig("subject", "Subject", 200));   
    columns.add(new ColumnConfig("NAME","NAME",100));
    columns.add(new ColumnConfig("TITLE","TITLE",100));
    ColumnConfig date = new ColumnConfig("date", "Date", 100);   
    date.setDateTimeFormat(DateTimeFormat.getFormat("MM/dd/y"));   
    columns.add(date);   
  
    ColumnModel cm = new ColumnModel(columns);   
  
    final Grid<ModelData> grid = new Grid<ModelData>(listStore, cm);   
    grid.setStateId("pagingGridExample");   
    grid.setStateful(true);   
    grid.addListener(Events.Attach, new Listener<GridEvent<ModelData>>() {   
      public void handleEvent(GridEvent<ModelData> be) {   
        PagingLoadConfig config = new BasePagingLoadConfig();   
        config.setOffset(0);   
        config.setLimit(5);   
           
        Map<String, Object> state = grid.getState();   
        if (state.containsKey("offset")) {   
          int offset = (Integer)state.get("offset");   
          int limit = (Integer)state.get("limit");   
          config.setOffset(offset);   
          config.setLimit(limit);   
        }   
        if (state.containsKey("sortField")) {   
          config.setSortField((String)state.get("sortField"));   
          config.setSortDir(SortDir.valueOf((String)state.get("sortDir")));   
        }   
        Boolean boolean1 =pageLoader.load(config);
        MessageBox.alert("b", boolean1.toString(), null);
      }   
    });   
    grid.setLoadMask(true);   
    grid.setBorders(true);   
    grid.setAutoExpandColumn("forum");   
  
    ContentPanel panel = new ContentPanel();   
    panel.setFrame(true);   
    panel.setCollapsible(true);   
    panel.setAnimCollapse(false);   
    panel.setIcon(Resources.ICONS.table());   
    panel.setHeading("Paging Grid");   
    panel.setLayout(new FitLayout());   
    panel.add(grid);   
    panel.setSize(600, 350);   
    panel.setBottomComponent(toolBar);   
    grid.getAriaSupport().setLabelledBy(panel.getId());   
    add(panel);   
  }   
  
}   
